import $hr from './index.js'

export default {
  config: {
    baseUrl: '',
    header: {},
    data: {},
    method: "GET",
    dataType: "json",
    responseType: "text",
    success() { },
    fail() { },
    complete() { }
  },
  interceptor: {
    request: null,
    response: null
  },
  request(options) {
    if (!options) {
      options = {}
    }
    this.config.header = {
        'Content-Type': options.contentType ? 'application/x-www-form-urlencoded' : 'application/json',
        'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token') || ''}` : '', //设置全局token
    }
    options.dataType = options.dataType || this.config.dataType
    options.url = $hr.config.SERVER_URL + options.url
    options.data = options.data || {}
    options.method = options.method || this.config.method

    return new Promise((resolve, reject) => {
      let _config = null
      options.complete = (response) => {
        let statusCode = response.statusCode
        response.config = _config
        if (this.interceptor.response) {
          let newResponse = this.interceptor.response(response)
          if (newResponse) {
            response = newResponse
          }
        }
        if (statusCode === 200) {
          if (response.data.code === 200) {
            console.log(options.url + '接口返回数据 ->')
            console.log(response.data)
            resolve(response.data)
          } else {
            $hr.methods.toast(response.data.message)
            reject(response.data)
          }
        } else if (statusCode === 401) {
          resolve({status: 401})
        } else {
          $hr.methods.toast('请求失败请检查网络')
          reject(response.data)
        }
      }

      _config = Object.assign({}, this.config, options)

      if (this.interceptor.request) {
        this.interceptor.request(_config)
      }
      uni.request(_config);
    });
  },
  get(url, data, options) {
    if (!options) {
      options = {}
    }
    options.url = url
    options.data = data
    options.method = 'GET'
    return this.request(options)
  },
  post(url, data, options) {
    if (!options) {
      options = {}
    }
    options.url = url
    options.data = data
    options.method = 'POST'
    return this.request(options)
  },
  put(url, data, options) {
    if (!options) {
      options = {}
    }
    options.url = url
    options.data = data
    options.method = 'PUT'
    return this.request(options)
  },
  delete(url, data, options) {
    if (!options) {
      options = {}
    }
    options.url = url
    options.data = data
    options.method = 'DELETE'
    return this.request(options)
  }
}
